<template>
  <div class="site-setting-page page-view">
    <!-- 面包屑导航 -->
    <div class="breadcrumb">
      <div class="list">
        <div class="home-icon">
          <i class="iconfont icon-home"></i>
        </div>
        <div class="item">
          <router-link to="/">
            <span class="text">首页</span>
          </router-link>
        </div>
        <div class="seperate">
          <i class="iconfont icon-arrow-right-thin"></i>
        </div>
        <div class="item">
          <router-link to="/setting">
            <span class="text">网站设置</span>
          </router-link>
        </div>
        <div class="seperate">
          <i class="iconfont icon-arrow-right-thin"></i>
        </div>
        <div class="item">
          <span class="text">APP设置</span>
        </div>
      </div>
      <h1 class="page-title">APP设置</h1>
    </div>

    <!-- 表单内容 -->
    <div class="form-container">
      <div class="v-card">
        <div class="card-header">
          <h3>APP图片设置</h3>
        </div>
        <div class="card-body">
          <div class="form-grid">
            <!-- 首页轮播图管理 -->
            <div class="form-group full-width">
              <label class="form-label">APP首页轮播图</label>
              <div class="upload-zone">
                <div class="carousel-images">
                  <div v-for="(banner, index) in homeBanners" :key="index" class="banner-item">
                    <ImageUploader
                      :modelValue="banner.url"
                      accept="image/jpeg,image/png"
                      :max-size="5"
                      @upload-success="handleCarouselUploadSuccess(index, $event)"
                      @update:modelValue="handleCarouselImageSelected(index, $event)"
                      @remove="deleteCarouselImage(index)"
                    />
                  </div>
                  <!-- 新增按钮 -->
                  <button class="add-btn" @click="addCarouselImage">
                    + 新增轮播图
                  </button>
                </div>
                <div class="form-hint">建议尺寸：750x300像素，JPG/PNG格式，大小不超过5MB</div>
              </div>
            </div>

            <!-- 我的页面顶图管理 -->
            <div class="form-group full-width">
              <label class="form-label">APP我的页面顶图</label>
              <div class="upload-zone">
                <ImageUploader
                  v-model="profileBanner"
                  accept="image/jpeg,image/png"
                  :max-size="5"
                  @upload-success="handleUploadSuccess('profile', $event)"
                  @update:modelValue="handleImageSelected('profile', $event)"
                  @remove="handleProfileBannerRemove"
                />
                <div class="form-hint">建议尺寸：750x200像素，JPG/PNG格式，大小不超过5MB</div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { useRouter } from "vue-router";
import { vToast } from '@/plugins/vToast';
import { get, post } from '@/utils/request';
import ImageUploader from '@/components/ImageUploader.vue';

const router = useRouter();
const settings = ref({});
const homeBanners = ref([]); // 改为数组，支持多张轮播图
const profileBanner = ref("");
const isSaving = ref(false);

// 获取所有设置
const fetchSettings = async () => {
  try {
    const res = await get("/setting/getAll");
    if (res && res.code === 200) {
      settings.value = res.data;
      
      // 处理首页轮播图 - 从swipper数组获取所有图片
      if (res.data.swipper && res.data.swipper.length > 0) {
        homeBanners.value = res.data.swipper.map(item => ({
          id: item.id || 0,
          url: item.url ? item.url.trim().replace(/`/g, '') : ''
        }));
      } else {
        // 如果没有数据，初始化一个空的轮播图
        homeBanners.value = [{ id: 0, url: '' }];
      }
      
      // 处理我的页面顶图 - 从profile数组中获取第一个图片的url
      if (res.data.profile && res.data.profile.length > 0 && res.data.profile[0].url) {
        profileBanner.value = res.data.profile[0].url.trim().replace(/`/g, '');
      } else {
        profileBanner.value = "";
      }
    }
  } catch (error) {
    vToast.error("获取设置失败");
    console.error("获取设置失败:", error);
    // 错误情况下也初始化一个空的轮播图
    homeBanners.value = [{ id: 0, url: '' }];
  }
};

// 初始化时获取设置
onMounted(() => {
  fetchSettings();
});

// 更新设置项
const updateSetting = async (type, url, id) => {
  try {
    isSaving.value = true;
    
    const res = await post("/setting/update", {
      id: id,
      type: type,
      url: url
    });
    if (res && res.code === 200) {
      vToast.success("保存成功");
      return true;
    } else {
      vToast.error(res?.msg || "保存失败");
      return false;
    }
  } catch (error) {
    vToast.error("保存设置失败");
    console.error("保存设置失败:", error);
    return false;
  } finally {
    isSaving.value = false;
  }
};

// 新增设置项
const addSetting = async (type, url) => {
  try {
    isSaving.value = true;
    
    const res = await post("/setting/add", {
      type: type,
      url: url
    });
    if (res && res.code === 200) {
      vToast.success("新增成功");
      // 返回新增的id
      return res.data && res.data.id ? res.data.id : 0;
    } else {
      vToast.error(res?.msg || "新增失败");
      return 0;
    }
  } catch (error) {
    vToast.error("新增设置失败");
    console.error("新增设置失败:", error);
    return 0;
  } finally {
    isSaving.value = false;
  }
};

// 删除设置项
const deleteSetting = async (id) => {
  try {
    isSaving.value = true;
    
    const res = await post("/setting/delete", {
      id: id
    });
    if (res && res.code === 200) {
      vToast.success("删除成功");
      return true;
    } else {
      vToast.error(res?.msg || "删除失败");
      return false;
    }
  } catch (error) {
    vToast.error("删除设置失败");
    console.error("删除设置失败:", error);
    return false;
  } finally {
    isSaving.value = false;
  }
};

// 处理上传成功
const handleImageSelected = (type, url) => {
  if (!url) return;
  
  switch (type) {
    case "profile":
      profileBanner.value = url;
      updateSetting("profile", url, 1); // 保持id为1
      break;
  }
};

// 处理个人页面顶图删除
const handleProfileBannerRemove = async () => {
  // 先调用删除接口
  const success = await deleteSetting(1); // 个人页面顶图的id固定为1
  if (success) {
    profileBanner.value = "";
  }
};

const handleUploadSuccess = (type, response) => {
  if (response.code !== 200) {
    vToast.error(response.msg || "上传失败");
    return;
  }

  vToast.success(response.msg || "上传成功");
  const url = response.data?.url;
  if (!url) {
    vToast.error("获取上传文件URL失败");
    return;
  }
  
  handleImageSelected(type, url);
};

// 轮播图相关处理函数
const handleCarouselImageSelected = async (index, url) => {
  if (!url) return;
  
  homeBanners.value[index].url = url;
  // 保存到后端
  const banner = homeBanners.value[index];
  
  if (banner.id > 0) {
    // 已有id，更新
    await updateSetting("swipper", url, banner.id);
  } else {
    // 无id，新增
    const newId = await addSetting("swipper", url);
    if (newId > 0) {
      homeBanners.value[index].id = newId;
    }
  }
};

const handleCarouselUploadSuccess = (index, response) => {
  if (response.code !== 200) {
    vToast.error(response.msg || "上传失败");
    return;
  }

  vToast.success(response.msg || "上传成功");
  const url = response.data?.url;
  if (!url) {
    vToast.error("获取上传文件URL失败");
    return;
  }
  
  handleCarouselImageSelected(index, url);
};

// 添加新的轮播图
const addCarouselImage = () => {
  homeBanners.value.push({ id: 0, url: '' });
};

// 删除轮播图
const deleteCarouselImage = async (index) => {
  const banner = homeBanners.value[index];
  
  // 如果有id，先调用删除接口
  if (banner.id > 0) {
    const success = await deleteSetting(banner.id);
    if (!success) {
      return;
    }
  }
  
  // 从数组中删除
  homeBanners.value.splice(index, 1);
  
  // 确保至少有一个轮播图
  if (homeBanners.value.length === 0) {
    homeBanners.value.push({ id: 0, url: '' });
  }
};
</script>
<style scoped lang="less">
.site-setting-page {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 40px);

  .breadcrumb {
    margin-bottom: 24px;
    
    .list {
      display: flex;
      align-items: center;
      font-size: 14px;
      color: #606266;
      
      .home-icon {
        margin-right: 8px;
        color: #909399;
        
        .iconfont {
          font-size: 18px;
        }
      }
      
      .item {
        margin-right: 8px;
        
        .text {
          color: #606266;
          transition: color 0.2s;
          
          &:hover {
            color: var(--v-theme);
          }
        }
      }
      
      .seperate {
        margin-right: 8px;
        color: #c0c4cc;
        
        .iconfont {
          font-size: 12px;
        }
      }
    }
    
    .page-title {
      margin-top: 16px;
      font-size: 24px;
      font-weight: 600;
      color: #303133;
    }
  }

  .form-container {
    width: 100%;
    padding: 24px;
    background-color: #ffffff;
    border-radius: 12px;
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.06);
    border: 1px solid #e8eef4;
    
    .v-card {
      border-radius: 10px;
      box-shadow: none;
      margin-bottom: 0;
      background: transparent;
      border: none;
      
      .card-header {
        padding: 0 0 20px 0;
        border-bottom: none;
        background: transparent;
        
        h3 {
          margin: 0;
          font-size: 18px;
          font-weight: 600;
          color: #2c3e50;
          letter-spacing: 0.5px;
        }
      }
      
      .card-body {
        padding: 0;
      }
    }
  }

  .form-grid {
    display: grid;
    grid-template-columns: repeat(1, 1fr);
    gap: 24px;
    
    .form-group {
      margin-bottom: 20px;
      
      &.full-width {
        grid-column: span 1;
      }
      
      .form-label {
        display: block;
        margin-bottom: 12px;
        font-size: 14px;
        font-weight: 500;
        color: #606266;
      }
      
      .upload-zone {
        .carousel-images {
          display: flex;
          flex-wrap: wrap;
          gap: 16px;
          margin-bottom: 16px;
          
          .banner-item {
            position: relative;
            width: 200px;
            
            .delete-btn {
              position: absolute;
              top: -10px;
              right: -10px;
              width: 24px;
              height: 24px;
              border-radius: 50%;
              background-color: #ff4d4f;
              color: white;
              border: none;
              cursor: pointer;
              display: flex;
              align-items: center;
              justify-content: center;
              font-size: 12px;
              transition: all 0.2s;
              
              &:hover {
                background-color: #ff7875;
                transform: scale(1.1);
              }
            }
          }
          
          .add-btn {
            width: 140px;
            height: 140px;
            border: 1px dashed #d9d9d9;
            background-color: #fafafa;
            border-radius: 8px;
            display: flex;
            align-items: center;
            justify-content: center;
            color: #8c8c8c;
            font-size: 14px;
            cursor: pointer;
            transition: all 0.3s;
            
            &:hover {
              border-color: var(--v-theme);
              color: var(--v-theme);
              background-color: rgba(24, 144, 255, 0.06);
            }
          }
        }
        
        .form-hint {
          margin-top: 8px;
          font-size: 12px;
          color: #8c8c8c;
          line-height: 1.5;
        }
      }
    }
  }

  @media (max-width: 768px) {
    padding: 12px;
    
    .form-container {
      padding: 16px;
    }
    
    .form-grid {
      .form-group {
        .upload-zone {
          .carousel-images {
            .banner-item,
            .add-btn {
              width: 100%;
            }
          }
        }
      }
    }
  }
}
</style>